﻿using System;
using System.Collections.Generic;
using System.Linq;
using oModbus.Utility;

namespace oModbus.Message
{
    /// <summary>
    /// 读取线圈响应
    /// </summary>
    public class ReadCoilResponse : AbstractModbusMessage
    {
        public ReadCoilResponse(byte slaveAddress, List<byte> coilState) : base(slaveAddress, FunctionCode.ReadCoil)
        {
            CoilState = coilState;
        }
        public ReadCoilResponse(byte[] messageBytes) : base(messageBytes)
        {
        }

        /// <summary>
        /// 内容字节数 1个字节	N*
        /// </summary>
        public byte ByteSize { get; private set; }

        private List<byte> _coilState;
        /// <summary>
        /// 线圈状态  n＝N或N+1
        /// </summary>
        public List<byte> CoilState
        {
            get { return _coilState; }
            set
            {
                _coilState = value;
                ByteSize = (byte)(_coilState.Count);
            }
        }

        protected override void Packing()
        {
            base.Packing();
            MessageData.Add(ByteSize);
            MessageData.AddRange(CoilState);
            Crc = MessageData.ToArray().CalculateCrc();

        }

        public override bool Analysis(byte[] messageBytes)
        {
            if (messageBytes.Length >= 5)
            {
                MessageData = messageBytes.ToList();
                SlaveAddress = messageBytes[0];
                FunctionCode = (FunctionCode)Convert.ToInt32(messageBytes[1]);
                ByteSize = messageBytes[2];
                var temp = new List<byte>();
                for (int i = 4; i < messageBytes.Length - 2; i++)
                {
                    temp.Add(messageBytes[i]);
                }
                _coilState = temp;
                Crc = new List<byte>()
                {
                    messageBytes[messageBytes.Length - 2],
                    messageBytes[messageBytes.Length - 1]
                }.ToArray();
                return true;
            }
            return false;
        }
    }
}
